<template>
	<section>
		<main class="filled fontc0">
			<mt-header fixed title="个人信息">
				<router-link to="/mine" slot="left">
					<mt-button icon="back"> </mt-button>
				</router-link>
			</mt-header>
			<ul class="ml20 mr15 fs14 mt50">
				<li class="head-pic" @click="updateHead">
					<div class="clearfix">
						<span class="fl">修改头像</span>
                        <span class="fr iconfont icon-jinruyou fontc3"></span>
						<span class="fr mr20">
							<img onerror="this.src='./static/imgs/man.png'" :src="info.userPortrait?info.userPortrait:'./static/imgs/man.png'" alt="" width="28" height="28">
						</span>
					</div>
					<input type="file"  name="files" id="test-image-file" value="" v-show="false">
					<div id="test-image-preview" v-show="false"></div>
					<div id="test-file-info" v-show="false"></div>
				</li>
				<li @click="updateNick">
					<div class="clearfix">
						<span class="fl">
							昵称
						</span>
                        <span class="fr iconfont icon-jinruyou fontc3"></span>
						<span class="fr fontc3 mr20">{{info.userName}}</span>
					</div>
				</li>
				<li @click="updateRealName">
					<div class="clearfix ">
						<span class="fl">
							真实姓名
						</span>
                        <span class="fr iconfont icon-jinruyou fontc3"></span>
						<span class="fr mr20 fontc3">{{info.realName}}</span>
					</div>
				</li>
				<li @click="changeSexVisiable=true">
					<div class=" clearfix">
						<span class="fl">
							性别
						</span>
                        <span class="fr iconfont icon-jinruyou fontc3"></span>
						<span class="fr mr20 fontc3">{{info.chinaSex}}</span>
					</div>
				</li>
				<li @click="showPositionPicker=true;">
					<div class="clearfix">
						<span class="fl">
							所在地
						</span>
                        <span class="fr iconfont icon-jinruyou fontc3"></span>
						<span class="fr fontc3">{{info.land}}</span>
					</div>
				</li>
				<li @click="open('date-picker')">
					<div class=" clearfix">
						<span class="fl">
							生日
						</span>
                        <span class="fr iconfont icon-jinruyou fontc3"></span>
						<span class="fr mr20 fontc3">{{info.birthday}}</span>
					</div>
				</li>
				<li @click="updateIntroduction">
					<div class="flex">
						<span class="fl">
							个人简介
						</span>
						<span class="fontc3 ml20 tr mr15 lh20 mt15 mb10 introduction">{{info.introduction}}</span>
                        <span class="iconfont icon-jinruyou fontc3"></span>
					</div>
				</li>
				<li>
                    <div class="clearfix">
                        <span class="fl">
                            银行卡
                        </span>
                        <span class="fr iconfont icon-jinruyou fontc3"></span>
                        <router-link to="/account/bindbank">
                            <span class="fr mr20 fontc3" v-show="info.cardState==0">未绑定</span>
                        </router-link>
                        <router-link to="/account/bindbank">
                            <span class="fr mr20 fontc3" v-show="info.cardState==1">未认证</span>
                        </router-link>
                        <span class="fr mr20 fontc3" v-show="info.cardState==2">已认证</span>
                    </div>
				</li>
				<li>
					<div class="clearfi">
						<span class="fl">
							手机认证
						</span>
                        <span class="fr iconfont icon-jinruyou fontc3"></span>
						<span class="fr mr20 fontc3">{{info.userPhone}}</span>
					</div>
				</li>
			</ul>
			<!-- 修改姓别的表单 -->
			<section>
				<mt-actionsheet
					:actions="changeSexActions"
					v-model="changeSexVisiable">
				</mt-actionsheet>
			</section>
			<transition name="slide-fade">
				<section class="positon-picker" v-show="showPositionPicker">
					<p class="lh40 fs16 flex">
						<span class="ml30 flex1" @click="showPositionPicker=false;">取消</span>
						<span class="mr30 flex1" @click="showPositionPicker=false;updateAddress();">确定</span>
					</p>
					<mt-picker
						:slots="positions"
						valueKey="fullname"
						@change="onPositionsChange">
					</mt-picker>
				</section>
			</transition>
			<transition name="slide-fade">
				<section>
					<mt-datetime-picker
						ref="date-picker"
						type="date"
						v-model="birthDate"
						year-format="{value} 年"
						month-format="{value} 月"
						date-format="{value} 日"
						@confirm="updateBirthday"
						:startDate="new Date('1900/01/01')"
						:endDate="new Date()">
					</mt-datetime-picker>
				</section>
			</transition>
		</main>
	</section>
</template>
<script>

import {MessageBox, Toast, Indicator, Actionsheet, Field, DatetimePicker} from 'mint-ui'
import axios from 'axios'

export default {
	name: "Info",
	data () {
		return {
			info : {},
			// 处理姓名的
			changeSexVisiable: false,
			changeSexActions : [
				{
					name: "男",
					method : () => {this.updateSex('男')},
				},
				{
					name: "女",
					method : () => {this.updateSex('女')},
				}
			],

			// 以下为position picker的配置
			positions: [
				{
					flex: 1,
					values: [],
					className: 'slot1',
					textAlign: 'right',
				},
				{
					flex: 1,
					values: [],
					className: 'slot2',
					textAlign: 'center',
				},
				{
					flex: 1,
					values: [],
					className: 'slot3',
					textAlign: 'left',
				},
			],

			province:[],
			city:    [],
			area:    [],
			userPosition: '',
			showPositionPicker: false,


			// 时间选择器picker~~`
			birthDate: null,
		}
	},
	mounted () {
		this.getInfo();
		this.getAllPosition();
	},
	methods : {
		open(picker) {
			this.$refs[picker].open();
		},
		// 地址选择的picker
		onPositionsChange (picker, values) {
			
			if (values[0] && values[0].cidx) {
				var cityIdxL = values[0].cidx[0];
				var cityIdxR = values[0].cidx[1];
				var citys = this.city.filter((value,idx,arr) => {
					return idx >= cityIdxL && idx < cityIdxR;
				});
				picker.setSlotValues(1,citys);
			};

			
			if (values[1] && values[1].cidx){
				var areaIdxL = values[1].cidx[0];
				var areaIdxR = values[1].cidx[1];
				var areas = this.area.filter((value,idx,arr) => {
					return idx >= areaIdxL && idx < areaIdxR;
				});
				picker.setSlotValues(2,areas);
			};
			
			var provinceStr= values[0] ? values[0].fullname : '';
			var cityStr    = values[1] ? values[1].fullname : '';
			var areaStr    = values[2] ? values[2].fullname : '';

			this.userPosition = provinceStr+ '-' +cityStr + '-' + areaStr;
		},
		getAllPosition () {
			Indicator.open('请求省市列表');
			function jsonpcallBack (json) {
				console.log(json);
			};

			// 列表请求只能通过跨域解决
			new Promise((resolve,reject) => {
				 window.callbackFun = (res) => {
					 Indicator.close();
					 if (res.status===0) {
						this.province = res.result[0];
						this.city     = res.result[1];
						this.area     = res.result[2];
						this.$set(this.positions[0],'values',this.province);
					} else {
						Toast('请求地址列表出错');
					};
				};
				
				let url = 'https://apis.map.qq.com/ws/district/v1/list';
				let data= {
					key     :'FH4BZ-4HGKW-QU3RR-OTVDU-5AJZ3-UZBSP',
					output  : 'jsonp',
					callback: 'callbackFun',
				};

				let script   = document.createElement('script');
				script.type  = "text/javascript";
				script.async = true;
				script.src   = url + '?' + Object.keys(data).map((key,idx) => key + '=' + data[key]).join('&');
				script.onerror = reject;
				document.body.appendChild(script);
			});
			return;
		},
		imgUpLoad () {
			var
			fileInput = document.getElementById('test-image-file'),
			info      = document.getElementById('test-file-info'),
			preview   = document.getElementById('test-image-preview');

			var _this = this;
			// 监听change事件:

			fileInput.addEventListener('change', function () {
				// 清除背景图片:
				preview.style.backgroundImage = '';
				// 检查文件是否选择:
				if (!fileInput.value) {
					info.innerHTML = '没有选择上传的文件';
					return;
				}
					// 获取File引用:
				var file = fileInput.files[0];
				// 获取File信息:
				info.innerHTML = '文件: ' + file.name + '<br>' +
								'大小: ' + file.size + '<br>' +
								'修改: ' + file.lastModifiedDate;
				if (file.type !== 'image/jpeg' && file.type !== 'image/png' && file.type !== 'image/gif') {
					Toast('不是有效的图片文件!');
					return;
				}
				
				if (file.size > 1 * 1024 * 1024) {
					Toast('选择文件须小于 1M，请重新选择');
					return;
				}

				// 读取文件:
				var reader = new FileReader();

				reader.onload = function(e) {
					var data = e.target.result;	// '...(base64编码)...'

					preview.style.backgroundImage = 'url(' + data + ')';

					var num = data.search(/,/) + 1;
					var str = data.substr(num);

					Indicator.open('头像上传中');
					axios({
						methods: "post",
						url: '/user/user/updatePic.do',
						params: {
							pic: str,
						}
					})
					.then((res) => {
						Indicator.close();
						res = res.data;

						if (res.code == 200) {
							_this.getInfo();
							Toast('修改成功');
						} else {
							Toast(res.msg);
						}
					}).catch(() => {
						Indicator.close();
						Toast('头像上传失败');
					})
				};
				// 以DataURL的形式读取文件:
				reader.readAsDataURL(file);
			});

			fileInput.click();
		},
		getInfo () {

			Indicator.open('加载用户信息');

			function findInfo() {
				return axios.get('/user/user/findInfo.do');
			};
			function showAuthentication() {
				return axios.get('/user/user/showAuthentication.do');
			};
			function findUserInfo() {
				return axios.get('/user/user/findUserInfo.do');
			};

			axios.all([findInfo(), showAuthentication(), findUserInfo()])
			.then(axios.spread( (res1,res2,res3) => {
				res1 = res1.data;
				res2 = res2.data;
				res3 = res3.data;

				if (res1.code == 200 && res2.code == 200 && res3.code == 200) {

					//上面三种都是遍历对象
					const info = {};
					Object.keys(res1.data).forEach((value) => {
						info[value] = res1.data[value];
					});
					Object.keys(res2.data).forEach((value) => {
						info[value] = res2.data[value];
					});
					Object.keys(res3.data).forEach((value) => {
						info[value] = res3.data[value];
					});
					this.info = info;
					
				} else if (res1.code == 503 || res2.code == 503 || res3.code == 503){
					this.$router.push({
						path : "/login"
					})
				} else {
					Toast(res1.msg);
					Toast(res2.msg);
					Toast(res3.msg);
				};
			}))
			.then(() => {
				Indicator.close();
			})
		},
		updateNick () {
            MessageBox.prompt(" ",
            {
                title: "请输入新的昵称",
                inputValue: this.info.userName?this.info.userName:' ',
                confirmButtonClass: "red"
            }).then(({ value, action }) => {
				Indicator.open();
				if (!value || !value.trim()) {
					return;
				};
				axios({
					methods: "post",
					url: '/user/user/updateNickName.do',
					params: {
						nickName: value.trim(),
					}
				})
				.then((res) => {
					Indicator.close();
					res = res.data;
					if (res.code == 200) {
						Toast('修改成功');
						this.getInfo();
					} else {
						Toast(res.msg);
					}
				})
			},() => {});
		},
		updateRealName () {

			MessageBox.prompt(" ",{
                title: "请输入姓名",
                inputValue: this.info.realName?this.info.realName:' ',
                confirmButtonClass: "red",
            }).then(({ value, action }) => {
				Indicator.open();
				if (!value || !value.trim()) {
					return;
				};
				axios({
					methods: "post",
					url: '/user/user/updateInfo.do',
					params: {
						realName: value.trim(),
					}
				})
				.then((res) => {
					Indicator.close();
					res = res.data;
					if (res.code == 200) {
						Toast('修改成功');
						this.getInfo();
					} else {
						Toast(res.msg);
					}
				})
			},() => {});
		},
		updateSex (pram) {
			if (pram === this.info.chinaSex) {
				return;
			} else {
				Indicator.open();
				axios({
					methods: "post",
					url: '/user/user/updateInfo.do',
					params: {
						userSex: pram=='男'?1:0,
					}
				})
				.then((res) => {
					Indicator.close();
					res = res.data;
					if (res.code == 200) {
						Toast('修改成功');
						this.getInfo();
					} else {
						Toast(res.msg);
					}
				})
			}
		},
		updateHead (pram) {
			// Toast('头像暂不可更改，请等待更新');
			this.imgUpLoad();
		},
		updateBirthday (value) {
			Indicator.open('更新地址');
			axios({
				methods: "post",
				url: '/user/user/updateInfo.do',
				params: {
					birthday : value.toLocaleDateString().replace(/\//g,'-'),
				}
			})
			.then((res) => {
				Indicator.close();
				res = res.data;
				if (res.code == 200) {
					Toast('修改成功');
					this.getInfo();
				} else {
					Toast(res.msg);
				}
			})
		},
		updateAddress () {
			Indicator.open('更新地址');
			axios({
				methods: "post",
				url: '/user/user/updateInfo.do',
				params: {
					land : this.userPosition,
				}
			})
			.then((res) => {
				Indicator.close();
				res = res.data;
				if (res.code == 200) {
					Toast('修改成功');
					this.getInfo();
				} else {
					Toast(res.msg);
				}
			})
		},
		updateIntroduction () {
			MessageBox.prompt(" ",{
                title: "请输入个人简介",
                inputValue: this.info.introduction?this.info.introduction:' ',
                confirmButtonClass: "red",
            }).then(({ value, action }) => {
				Indicator.open();
				if (!value || !value.trim()) {
					return;
				};
				if (value.trim().length > 200) {
					Toast('简介长度不能大于200字符');
					return;
				};
				axios({
					methods: "post",
					url: '/user/user/updateInfo.do',
					params: {
						introduction: value.trim(),
					}
				})
				.then((res) => {
					Indicator.close();
					res = res.data;
					if (res.code == 200) {
						Toast('修改成功');
						this.getInfo();
					} else {
						Toast(res.msg);
					}
				})
			});
		},
		onValuesChange(picker, values) {
			if (values[0] > values[1]) {
				picker.setSlotValue(1, values[0]);
			}
		}
	}
}
</script>

<style scoped>
	.head-pic {
		position: relative;
	}
	
	.birthday-picker{
		position: fixed;
		background-color: red;
		width: 100%;
		left: 0;
		bottom: 0;
	}
	img{
        width: 28px;
        height: 28px;
        border-radius: 14px;
        overflow: hidden;
	}
	li{
		line-height: 50px;
        margin-top: 5px;
        border-bottom: 1px solid #F9F9FA;
	}
	li span.fl {
        white-space: nowrap;
    }
    .introduction{
        white-space: initial;
        flex: 1;
        overflow: hidden;
    }
	.positon-picker{
		position: fixed;
		width: 100%;
		left: 0;
        bottom: 0;
        background-color: #fff;
        border-top: 1px solid #efefef;
	}
    .positon-picker p {
        border-bottom: 1px solid #fff;
    }
	.slide-fade-enter-active {
		transition: all 0.3s ease;
	}
	.slide-fade-leave-active {
		transition: all 0.3s ease;
	}
	.slide-fade-enter, .slide-fade-leave-to {
		transform: translateY(220px);
	}
</style>





